Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Encapsulation in java

Encapsulation Intro

What is Encapsulation?

Encapsulation in Java is a fundamental concept in object-oriented programming (OOP) that refers to the bundling of data and methods that operate on that data within a single unit, which is called a class in Java. It is a way of hiding the implementation details of a class from outside access and only exposing a public interface that can be used to interact with the class.

How is Encapsulation Achieved in Java?

In Java, encapsulation is achieved by declaring the instance variables of a class as private, which means they can only be accessed within the class. To allow outside access to the instance variables, public methods called getters and setters are defined, which are used to retrieve and modify the values of the instance variables, respectively. By using getters and setters, the class can enforce its own data validation rules and ensure that its internal state remains consistent. Example of Encapsulation in Java Here’s a simple example of encapsulation in Java:
Encapsulation basic example in java with getters and setters class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String[] args) { Person person = new Person(); person.setName("John"); person.setAge(30); System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } }

Output

Name: John Age: 30
In this example, Person is a class that has private instance variables name and age. The class provides public getter and setter methods to access and modify these variables.

Advantages of Encapsulation

Data Hiding: Encapsulation is a way of restricting the access of our data members by hiding the implementation details. ✦ Increased Flexibility: We can make the class read-only or write-only by providing only a getter or setter method. ✦ Reusability: Encapsulation also provides a way for data hiding. ✦ Testing: The encapsulated class is easy to test. Note : Encapsulation in Java is a powerful tool that helps manage complexity in large programs by hiding the implementation details and exposing only the necessary functionality.

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★Encapsulation

Tutorials